package com.atguigu.datastream.day05;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink08_Flink_ForMonotonous_WaterMark
 * Package: com.atguigu.day05
 * Description:
 *           有序流创建水位线
 * @Author ChenJun
 * @Create 2023/4/11 18:31
 * @Version 1.0
 */
public class Flink08_ForMonotonous_WaterMark {
    public static void main(String[] args) throws Exception {

        //1. 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3. 将数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> WaterSensor =
                streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String s) throws Exception {
                String[] split = s.split(",");

                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //TODO 4.指定WaterMark以及事件时间戳   使用有序流中的WaterMark
        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = WaterSensor.assignTimestampsAndWatermarks(WatermarkStrategy
                //指定WaterMark
                .<WaterSensor>forMonotonousTimestamps()
                //分配事件时间戳
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor waterSensor, long l) {
                        return waterSensor.getTs() * 1000;
                    }
                })
        );

        //5. 将相同id的数据聚合到一块
        KeyedStream<com.atguigu.datastream.bean.WaterSensor, Tuple> keyedStream = waterSensorSingleOutputStreamOperator.keyBy("id");

        //TODO 6.开启一个基于事件时间的滚动窗口，窗口大小为5S
        WindowedStream<com.atguigu.datastream.bean.WaterSensor, Tuple, TimeWindow> window = keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(5)));

        SingleOutputStreamOperator<String> process = window.process(new ProcessWindowFunction<com.atguigu.datastream.bean.WaterSensor, String, Tuple, TimeWindow>() {
            @Override
            public void process(Tuple tuple, ProcessWindowFunction<com.atguigu.datastream.bean.WaterSensor, String, Tuple, TimeWindow>.Context context, Iterable<com.atguigu.datastream.bean.WaterSensor> elements, Collector<String> out) throws Exception {
                String msg =
                        "窗口: [" + context.window().getStart() / 1000 + "," + context.window().getEnd() / 1000 + ") 一共有 "
                                + elements.spliterator().estimateSize() + "条数据 ";
                out.collect(msg);
            }
        });

        SingleOutputStreamOperator<WaterSensor> vc = window.sum("vc");

        process.print();
        vc.print();

        env.execute();


    }
}
